package org.zpmis.api.business;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.zpmis.common.base.AdminLoginUser;
import org.zpmis.common.base.BaseWebService;
import org.zpmis.common.exception.BusinessException;
import org.zpmis.common.result.ResultCode;
import org.zpmis.common.utils.StringUtil;
import org.zpmis.domain.user.enums.EmployeeEnum;
import org.zpmis.domain.user.model.Employee;
import org.zpmis.domain.user.model.SysUser;
import org.zpmis.domain.user.qo.*;
import org.zpmis.domain.user.service.EmployeeService;
import org.zpmis.domain.user.service.SysUserService;
import org.zpmis.domain.user.vo.EmployeeListVo;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with CodeGenerator
 * Description:
 * @author  Yang
 * Date: 2021-6-24
 * Time: 15:48:45
 */
@Service
@Slf4j
public class EmployeeWebService extends BaseWebService {
     @Reference
     private EmployeeService employeeService;

     @Reference
     private SysUserService sysUserService;

    /**
     * 新增员工
     * @param addEmployeeQo
     * @throws BusinessException
     * @throws Exception
     */
    public void addEmployee(AddEmployeeQo addEmployeeQo) throws BusinessException,Exception{
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        employeeService.save(
            Employee.builder()
                    .number(addEmployeeQo.getNumber())
                    .phone(addEmployeeQo.getPhone())
                    .cardType(addEmployeeQo.getCardType())
                    .idCard(addEmployeeQo.getIdCard())
                    .name(addEmployeeQo.getName())
                    .age(addEmployeeQo.getAge())
                    .sex(addEmployeeQo.getSex())
                    .orgId(addEmployeeQo.getOrgId())
                    .type(addEmployeeQo.getType())
                    .status(addEmployeeQo.getStatus())
                    .createTime(Instant.now().toEpochMilli())
                    .createId(adminLoginUser.getId())
                    .updateTime(Instant.now().toEpochMilli())
                    .isDeleted(EmployeeEnum.NOT_DELETE.code())
                    .build()
            );
    }

    /**
     * 修改员工信息
     * @param editEmployeeQo
     * @throws BusinessException
     * @throws Exception
     */
    public void editEmployee(EditEmployeeQo editEmployeeQo) throws BusinessException,Exception{
        Long id = editEmployeeQo.getId();
        Employee employee = employeeService.findById(id);
        if(employee == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        employee.setNumber(editEmployeeQo.getNumber());
        employee.setPhone(editEmployeeQo.getPhone());
        employee.setCardType(editEmployeeQo.getCardType());
        employee.setIdCard(editEmployeeQo.getIdCard());
        employee.setName(editEmployeeQo.getName());
        employee.setSex(editEmployeeQo.getSex());
        employee.setAge(editEmployeeQo.getAge());
        employee.setOrgId(editEmployeeQo.getOrgId());
        employee.setType(editEmployeeQo.getType());
        employee.setStatus(editEmployeeQo.getStatus());
        employee.setUpdateTime(Instant.now().toEpochMilli());
        employee.setUpdateId(adminLoginUser.getId());
        employeeService.update(employee);
    }

    /**
     * 员工列表查询
     * @param employeeListQo
     * @return
     * @throws BusinessException
     * @throws Exception
     */
    public PageInfo employeeList(EmployeeListQo employeeListQo) throws BusinessException,Exception{
        String number = employeeListQo.getNumber();
        String phone = employeeListQo.getPhone();
        Integer cardType = employeeListQo.getCardType();
        String idCard = employeeListQo.getIdCard();
        String name = employeeListQo.getName();
        Integer sex = employeeListQo.getSex();
        Long orgId = employeeListQo.getOrgId();
        Integer type = employeeListQo.getType();
        Integer status = employeeListQo.getStatus();
        Condition condition = new Condition(Employee.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",EmployeeEnum.NOT_DELETE.code());
        if(StringUtil.isNotEmpty(number)){
            criteria.andLike("number","%"+number+"%");
        }
        if(StringUtil.isNotEmpty(phone)){
            criteria.andLike("phone","%"+phone+"%");
        }
        if(StringUtil.isNotEmpty(idCard)){
            criteria.andLike("idCard","%"+idCard+"%");
        }
        if(StringUtil.isNotEmpty(name)){
            criteria.andLike("name","%"+name+"%");
        }
        if(cardType != null){
            criteria.andEqualTo("cardType",cardType);
        }
        if(sex != null){
            criteria.andEqualTo("sex",sex);
        }
        if(orgId != null){
            criteria.andEqualTo("orgId",orgId);
        }
        if(type != null){
            criteria.andEqualTo("type",type);
        }
        if(status != null){
            criteria.andEqualTo("status",status);
        }
        condition.orderBy("createTime").desc();
        PageHelper.startPage(employeeListQo.getPageNum(),employeeListQo.getPageSize());
        List<Employee> employeeList = employeeService.findByCondition(condition);
        PageInfo pageInfo = new PageInfo(employeeList);
        //返回自定义实体
        List<EmployeeListVo> resultList = employeeList.stream().map(EmployeeListVo::new).collect(Collectors.toList());
        pageInfo.setList(resultList);
        return pageInfo;
    }

    /**
     * 员工入职
     * @param empInductionQo
     * @throws BusinessException
     * @throws Exception
     */
    public void empInduction(EmpInductionQo empInductionQo) throws BusinessException,Exception{
        Long id = empInductionQo.getId();
        Long orgId = empInductionQo.getOrgId();
        Employee employee = employeeService.findById(id);
        if(employee == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        employeeService.update(
        Employee.builder()
                .id(id)
                .status(EmployeeEnum.ON_THE_JOB.code())
                .orgId(orgId)
                .updateId(adminLoginUser.getId())
                .updateTime(Instant.now().toEpochMilli())
                .build()
        );
    }


    /**
     * 员工离职
     * @param empDimissionQo
     * @throws BusinessException
     * @throws Exception
     */
    public void empDimission(EmpDimissionQo empDimissionQo) throws BusinessException,Exception{
        Long id = empDimissionQo.getId();
        Employee employee = employeeService.findById(id);
        if(employee == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        employeeService.update(
                Employee.builder()
                        .id(id)
                        .status(EmployeeEnum.DIMISSION.code())
                        .updateId(adminLoginUser.getId())
                        .updateTime(Instant.now().toEpochMilli())
                        .build()
        );
    }

    /**
     * 员工分配账号
     * @param empDistributionAccountQo
     * @throws BusinessException
     * @throws Exception
     */
    public void empDistributionAccount(EmpDistributionAccountQo empDistributionAccountQo)  throws BusinessException,Exception{
        Long id = empDistributionAccountQo.getId();
        Employee employee = employeeService.findById(id);
        if(employee == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        Long sysUid = empDistributionAccountQo.getSysUid();
        // 判断账号是否可用
        SysUser sysUser = sysUserService.findById(sysUid);
        if(sysUser == null || !sysUser.getAccountNonExpired() || !sysUser.getAccountNonLocked() || !sysUser.getCredentialsNonExpired() || !sysUser.getEnabled() || sysUser.getIsDeleted()){
            //账号不可用
            throw new BusinessException(ResultCode.USER_ACCOUNT_DISABLE);
        }
        Condition condition = new Condition(Employee.class);
        condition.createCriteria()
                .andNotEqualTo("id",id)
                .andEqualTo("sysUid",sysUid)
                .andEqualTo("isDeleted",EmployeeEnum.NOT_DELETE.code())
                .andEqualTo("status",EmployeeEnum.ON_THE_JOB.code());
        List<Employee> employeeList = employeeService.findByCondition(condition);
        if(!employeeList.isEmpty()){
            //不为空 说明该账号已经分配给其他员工 不可重复分配
            throw new BusinessException(ResultCode.SYS_ACCOUNT_OCCUPIED);
        }
        employeeService.update(
                Employee.builder()
                        .id(id)
                        .sysUid(sysUid)
                        .updateId(adminLoginUser.getId())
                        .updateTime(Instant.now().toEpochMilli())
                        .build()
        );
    }
}
